<!--#layout name=default-->
<div id="main" class="offset-top" v-cloak>
  <div class="container">
    <div class="row">
      <div class="col-md-8 col-md-offset-2">
        <div class="page-header">
          <h1 class="title">Share a website</h1>
        </div>
        <kb-form
          simple
          class="form-horizontal"
          :model="model"
          :rules="rules"
          ref="form"
        >
          <div class="note note-info">
            <p>{{Kooboo.text.site.sites.shareTip}}</p>
          </div>
          <kb-form-item class="form-group" prop="siteName" v-slot="error">
            <div :class="{'has-error' : !!error.error}">
              <label class="col-md-2 control-label">Site name</label>
              <div class="col-md-10 row">
                <div class="col-md-6">
                  <input
                    type="text"
                    class="form-control input-medium"
                    placeholder="Site name"
                    v-model="model.siteName"
                    v-kb-tooltip:right.manual.error="error.error"
                  />
                </div>
              </div>
            </div>
          </kb-form-item>
          <kb-form-item class="form-group">
            <label class="col-md-2 control-label">Tags</label>
            <div class="col-md-10">
              <select
                multiple
                class="form-control"
                v-kb-select2="tagSelect2"
              ></select>
            </div>
          </kb-form-item>
          <kb-form-item class="form-group">
            <label class="col-md-2 control-label">Description</label>
            <div class="col-md-10">
              <textarea
                v-model="model.description"
                class="form-control autosize"
              ></textarea>
            </div>
          </kb-form-item>
          <kb-form-item class="form-group">
            <label class="col-md-2 control-label">Link</label>
            <div class="col-md-10">
              <input
                class="form-control"
                placeholder="publisher url"
                v-model="model.link"
              />
            </div>
          </kb-form-item>
          <kb-form-item class="form-group">
            <label class="col-md-2 control-label">Thumbnails</label>
            <div class="col-md-10">
              <div class="fileinput">
                <span class="btn btn-default btn-file"
                  ><span>Select images</span>
                  <input
                    id="edit_file"
                    type="file"
                    v-kb-upload="{
                        allowMultiple: true,
                        acceptTypes: ['image/bmp','image/png','image/jpg','image/jpeg'],
                        acceptSuffix: ['bmp', 'png', 'jpg', 'jpeg'],
                        callback: uploadImg
                    }"
                  /> </span
                >&nbsp;
                <span v-if="!model.images.length">
                  <span>Support types: bmp, png, jpg, jpeg.</span>
                  &nbsp;
                  <span>{{Kooboo.text.site.sites.automatically}}</span>
                </span>
                <span v-if="model.images.length"
                  >Click the image below to select cover image.</span
                >
              </div>
              <div class="file-list img-list">
                <ul v-if="model.images.length">
                  <li
                    v-for="( $data,index) in model.images"
                    :key="index"
                    :class="{active: index==model.defaultImg}"
                    @click="model.defaultImg=index"
                  >
                    <div class="fileinput-new thumbnail">
                      <img
                        :src="$data.data?$data.data:$data"
                        style="width: 100px; height: 100px;"
                      />
                    </div>
                    <a
                      href="javascript:;"
                      @click.stop="removeFile($data,index)"
                      v-kb-tooltip="Kooboo.text.common.remove"
                      ><i class="fa fa-remove"></i
                    ></a>
                  </li>
                </ul>
              </div>
            </div>
          </kb-form-item>
          <ul class="pager">
            <li class="next"
              ><button @click="onShare" class="btn blue">Share</button></li
            >
            <li class="previous"
              ><a href="javascript:;" @click.stop="SPAClick" class="btn gray"
                >Return</a
              ></li
            >
          </ul>
        </kb-form>
      </div>
    </div>
  </div>
</div>
<script>
  (function() {
    Kooboo.loadJS([
      "/_Admin/Scripts/lib/select2.min.js",
      "/_Admin/Scripts/lib/jquery.textarea_autosize.min.js",
      "/_Admin/Scripts/SPA.js",
      "/_Admin/Scripts/components/kbForm.js"
    ]);
    Kooboo.loadCSS(["/_Admin/Styles/select2/select2.css"]);
  })();
  var self = new Vue({
    el: "#main",
    data: function() {
      return {
        model: {
          siteName: "",
          isPrivate: false,
          description: "",
          link: "",
          images: [],
          defaultImg: 0
        },
        tagSelect2: {
          options: [
            Kooboo.text.site.share.corporation,
            Kooboo.text.site.share.article,
            Kooboo.text.site.share.category
          ],
          selected: []
        },
        rules: {
          siteName: [
            { required: Kooboo.text.validation.required },
            {
              pattern: /^[A-Za-z][\w\-]*$/,
              message: Kooboo.text.validation.siteNameInvalid
            }
          ]
        }
      };
    },
    mounted: function() {
      var self = this;
      Kooboo.Site.getName().then(function(res) {
        if (res.success) {
          self.model.siteName = res.model;
        }
      });
      setTimeout(function() {
        $(".autosize")
          .textareaAutoSize()
          .trigger("keyup");
      }, 300);
    },
    methods: {
      onShare: function() {
        if (self.$refs.form.validate()) {
          var data = new FormData();

          data.append("siteName", self.model.siteName);
          data.append("isPrivate", false);
          data.append("description", self.model.description || "");
          data.append("link", self.model.link || "");

          data.append(
            "tags",
            self.tagSelect2.selected
              .map(function(m) {
                return m.text;
              })
              .join(",")
          );

          if (self.model.images.length) {
            data.append(
              "images",
              JSON.stringify(
                self.model.images.map(function(f) {
                  if (typeof f != "string") return f.file.name;
                  return f;
                })
              )
            );

            self.model.images.forEach(function(f, index) {
              if (typeof f != "string") {
                data.append("file_" + index, f.file);
              }
            });
          }

          data.append(
            "defaultImg",
            self.model.images.length ? self.model.defaultImg : -1
          );

          Kooboo.Template.Share(data).then(function(res) {
            if (res.success) {
              location.href = Kooboo.Route.Get(Kooboo.Route.Site.TemplatePage, {
                type: "personal"
              });
            }
          });
        }
      },
      SPAClick: function() {
        self.$refs.form.clearValid();
        self.$nextTick(function() {
        Kooboo.SPA.getView(Kooboo.Route.Site.ListPage, {
          container: '[layout="default"]'
        });
      });
      },
      removeFile: function(item, index) {
        var selected = self.model.images[self.model.defaultImg];
        self.model.images.splice(index, 1);
        if (index == self.model.defaultImg) {
          if (index > 0) self.model.defaultImg = index - 1;
          else self.model.defaultImg = 0;
        } else {
          self.model.defaultImg = self.model.images.indexOf(selected);
        }
      },
      uploadImg: function(data, files) {
        files.forEach(function(f) {
          var reader = new FileReader();
          reader.onloadend = function() {
            self.model.images.push({
              data: reader.result,
              file: f
            });
          };
          reader.readAsDataURL(f);
        });
      }
    }
  });
</script>
